import Vue from 'vue'
import Vuex from 'vuex'
import { getUserInfoApi, getUserProfileApi } from '@/api/userApi.js'

Vue.use(Vuex)

// 定义一个变量保存state数据
let initState = {
  // 存储token信息
  tokenInfo: {},
  // 用户信息
  userInfo: {},
  // 简介信息
  userProfile: {}
}
// 读取localstorage数据
const stateStr = localStorage.getItem('state')
// 判断是否有数据
if (stateStr) {
  initState = JSON.parse(stateStr)
}
export default new Vuex.Store({
  state: initState,
  mutations: {
    // 更新tokenInfo数据
    updateTokenInfo (state, payload) {
      state.tokenInfo = payload
      // 每次更新，调用savestate方法
      this.commit('saveStateToStorage')
    },
    // 存储到localstorage里
    saveStateToStorage (state) {
      localStorage.setItem('state', JSON.stringify(state))
    },
    updateUserInfo (state, payload) {
      state.userInfo = payload
      // mutation调用mutation
      this.commit('saveStateToStorage')
    },
    // 用户简介存储
    updateUserProfile (state, payload) {
      state.userProfile = payload
      // mutation调用mutation
      this.commit('saveStateToStorage')
    },
    // 退出登录，清空数据
    cleanState (state) {
      // 清空vuex数据
      state.tokenInfo = {}
      state.userInfo = {}
      state.userProfile = {}
      // 调用saveStateToStorage，把本地清空
      this.commit('saveStateToStorage')
    }
  },
  actions: {
   async initUserInfo (ctx) {
      const { data: res } = await getUserInfoApi()
      if (res.message === 'OK') {
         // TODO:转交给mutation
      ctx.commit('updateUserInfo', res.data)
      }
    },
   async initUserProfile (ctx) {
     const { data: res } = await getUserProfileApi()
     if (res.message === 'OK') {
        //  把简介转交给mutation
     ctx.commit('updateUserProfile', res.data)
     }
    }
  },
  modules: {
  },
  // 计算属性
  getters: {
    // 动态返回头像
    userAvatar (state) {
      // 定义一个默认头像
      let imgSrc = 'https://img.yzcdn.cn/vant/cat.jpeg'
      // 如果用户头像不为空，以photo为准
      if (state.userInfo.photo) {
        imgSrc = state.userInfo.photo
      }
      return imgSrc
    }
  }
})
